package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;

    @Override
    public long addTask(Task task) {

//        保存相关的信息
        boolean flag = saveTaskinfoOrLogs(task);

        if (flag) {
//            添加数据到redis中
            addRedisTaskInfo(task);
        }
        return task.getTaskId();

    }

    @Override
    public boolean cancleTask(long taskId) {

        boolean flag= false;

//        修改数据库中内容
        try {
            Task task = updateTaskSchedle(taskId, ScheduleConstants.CANCELLED);

            if (task != null) {
                //        删除redis数据
                deleteTask(task);
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;

    }

    //        删除redis数据
    private void deleteTask(Task task) {


        String key = task.getTaskType() + "_" + task.getPriority();

//        删除redis中内容
        try {
            if (task != null) {
                if (task.getExecuteTime() <= System.currentTimeMillis()) {
                    //                删除当前任务

                    cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
                } else {
                    cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private Task updateTaskSchedle(Long taskId, int status) {
        //        修改数据库中数据
        Task task = null;
        try {
            taskinfoMapper.deleteById(taskId);
//        修改日志表
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);//关闭任务
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();

            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(new Date().getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return task;
    }

    //            添加数据到redis中
    private void addRedisTaskInfo(Task task) {

        String key = task.getTaskType() + "_" + task.getPriority();

//        设置一个未来五分中,获取5分钟之后的时间  毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
//        获取毫秒值
        long timeInMillis = calendar.getTimeInMillis();

//           如果任务的执行时间小于等于当前时间，存入list
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= timeInMillis) {
//          如果任务的执行时间大于当前时间 && 小于等于预设时间（未来5分钟） 存入zset中
            cacheService.zAdd(ScheduleConstants.FUTURE + key,
                    JSON.toJSONString(task), task.getExecuteTime());
        }

    }

    private boolean saveTaskinfoOrLogs(Task task) {
        boolean flag = false;

        try {
//        添加Taskinfo
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
//            返回任务id
            task.setTaskId(taskinfo.getTaskId());

//          添加TaskinfoLogs表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);//初始化
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (BeansException e) {
            e.printStackTrace();
        }

        return flag;
    }


    /**
     * 消费任务
     *
     * @param type      消费方式
     * @param priority 优先级
     * @return
     */
    @Override
    public Task pullTask(Integer type, Integer priority) {

        Task task = null;

        String key = type + "_" + priority;

//        从redis中获取数据任务
        String data = cacheService.lRightPop(ScheduleConstants.TOPIC + key);

        if (StringUtils.isNotEmpty(data)) {
            //        转化为task对象
            task = JSON.parseObject(data, Task.class);

//        修改数据库内容
            updateTaskSchedle(task.getTaskId(), ScheduleConstants.EXECUTED);
        }
        return task;
    }


    //    定时任务同步到list中消费,未来数据定时刷新
    @Scheduled(cron = "0 */1 * * * ?")//每份中执行一次
    public void cancleTaskList() {

//        加锁解决分布式抢占问题
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if (StringUtils.isNotBlank(token)) {
            log.info("开始消费了********");
//        获取所有未来将要消费的数据
            Set<String> data = cacheService.scan(ScheduleConstants.FUTURE + "*");

            for (String futureKey : data) {

//            获取当前组的key
                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                //获取该组key下当前需要消费的任务数据
                Set<String> task = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

                if (task != null) {
                    cacheService.refreshWithPipeline(futureKey, topicKey, task);
                    System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                }
            }
        }
    }


    //    数据库数据同步到redis中
    @PostConstruct//开机时加载
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData() {

//        清理redis中数据
        deleteTaskRedis();

//        查询数据库中数据,当前小于等于执行时间5分钟
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        QueryWrapper<Taskinfo> wrapper = new QueryWrapper<>();
        wrapper.le("execute_time", calendar.getTime());
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(wrapper);

//        同步到redis中
        if (taskinfos != null) {
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addRedisTaskInfo(task);
            }
        }
    }

    //        清理redis中数据
    private void deleteTaskRedis() {
        Set<String> topicKey = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKey = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(topicKey);
        cacheService.delete(futureKey);
    }
}